/**
 * Licensed to CMIM,Inc. under the terms of the CMIM * Software License version 1.0.
 * See the NOTICE file distributed with this work for additional * information regarding copyright ownership.
 * ---------------------------------------------------------------------------- * Date Author Version
 * 2019/3/16 neusoft 1.0
 **/

package com.xnyzc.lhy.common.component.payment;
/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

import com.xnyzc.lhy.common.constant.PayConstant;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {

    /**
     * 微信公众平台：“微信支付”--》“商户信息”--》“商户号”，将该值赋值给partner
     */
    private static String partner;


    @Value("${global.weChat.pay.partnerId}")
    public void setPartnerId(String partnerId) {
        partner = partnerId;
    }

    /**
     * p12证书的位置
     * 微信公众平台：“微信支付”--》“商户信息”--》“交易数据”--》“详情请登录微信支付商户平台查看”（登录）--》“API安全”--》“API证书”--》“下载证书”
     * 下载证书后将apiclient_cert.p12放在src目录下面（出于安全考虑，请自行下载自己的证书）
     *
     * @param url
     * @param data
     * @return
     * @throws Exception
     */
    public static String doRefund(String url, String data) throws Exception {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        // P12文件目录
        FileInputStream inputStream = new FileInputStream(new File(PayConstant.WX_APICLIENT_CERT));
        keyStore.load(inputStream, partner.toCharArray());
        // 这里也是写密码的
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, partner.toCharArray())
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
            // 设置响应头信息
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.addHeader("Host", "api.mch.weixin.qq.com");
            httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpPost.addHeader("Cache-Control", "max-age=0");
            httpPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpPost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } catch (IOException e) {
            } finally {
                response.close();
            }
        } catch (IOException e) {
        } finally {
            httpclient.close();
        }
        return "";
    }

}
